const wholePath = window.document.location.href;
const pathName = window.document.location.pathname;
const pathLength = wholePath.indexOf(pathName);
const hostPath = wholePath.substring(0, pathLength);
const projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);

const fn = {
  //行拖拽
  rowDrop(dom, _this) {
    const that = _this;
    return new Promise((resolve, reject) => {
      const tbody = document.querySelector('.' + dom + ' tbody');
      that.$sortable.create(tbody, {
        onEnd({newIndex, oldIndex}) {
          console.log(newIndex);
          console.log(oldIndex);
          const currRow = that.tableData.splice(oldIndex, 1)[0];
          console.log(currRow);
          that.tableData.splice(newIndex, 0, currRow);
          resolve('promise');
        }
      })
    })
  },
  //列拖拽
  columnDrop(dom, _this) {
    const that = _this;
    const wrapperTr = document.querySelector('.' + dom + ' tr');
    that.$sortable.create(wrapperTr, {
      animation: 180,
      delay: 0,
      onEnd: evt => {
        const oldItem = that.dropCol[evt.oldIndex];
        that.dropCol.splice(evt.oldIndex, 1);
        that.dropCol.splice(evt.newIndex, 0, oldItem)
      }
    })
  },
};

const setSessionStorage = function (key, objData) {
  if (typeof objData == 'string') {
    sessionStorage.setItem(key, objData);
  } else {
    sessionStorage.setItem(key, JSON.stringify(objData));
  }
};

const getSessionStorage = function (key, isObj) {
  let data = sessionStorage.getItem(key);
  if (isObj) {
    return JSON.parse(data);
  }
  return data;
};

const removeSessionStorage = function (key) {
  sessionStorage.removeItem(key);
};

const install = function (Vue, options) {
  let _this = Vue.prototype;
  let Common = Vue.prototype.$common = {};

  Common.wholePath = wholePath;
  Common.pathName = pathName;
  Common.pathLength = pathLength;
  Common.hostPath = hostPath;
  Common.projectName = projectName;
  Common.fn = fn;

  /**
   * 在新页面打开
   */
  Common.OpenNewPage = function ($this, routePath, param) {
    let routeData = $this.$router.resolve({
      path: routePath,
      query: param
    });
    window.open(routeData.href, '_blank');
  };

  /**
   * 写入sessionStorage
   */
  Common.setSessionStorage = setSessionStorage;

  /**
   * 读取sessionStorage
   */
  Common.getSessionStorage = getSessionStorage;

  /**
   * 移除sessionStorage
   */
  Common.removeSessionStorage = removeSessionStorage;

  /**
   * 时间戳转时间
   */
  Common.timestampToTime = function (row, column) {
    var date = row[column.property];
    if (date == undefined) {
      return "";
    }
    return moment(date).format("YYYY-MM-DD HH:mm:ss");
  };

  Common.isSuccess = function (data, callback) {
    if (data && data.data) {
      var json = data.data;
      if (json.status == 'SUCCESS') {
        _this.$message({message: '执行成功', type: "success"});
        callback(json);
      } else if (json.message) {
        _this.$message({message: json.message, type: "error"});
      }
    } else {
      _this.$message({message: '执行异常，请重试', type: "error"});
    }
  }
};

const getQueryObject = function (url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf('?') + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
};

const cleanArray = function (actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
};

const json2Param = function (json) {
  if (!json) return '';
  let res = cleanArray(Object.keys(json).map(key => {
    if (json[key] === undefined) return '';
    return encodeURIComponent(key) + '=' +
      encodeURIComponent(json[key]);
  })).join('&');
  return res;
};

const param2Obj = function (url) {
  const search = url.split('?')[1];
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
};

const html2Text = function (val) {
  const div = document.createElement('div');
  div.innerHTML = val;
  return div.textContent || div.innerText;
};


// 获取手机号码归属运营商:
// 中国手机号段（截止19年5月）：13[0-9], 14[0,1,4,5,6,7,8]（14开头为数据卡或物联网卡）, 15[0, 1, 2, 3, 5, 6, 7, 8, 9],165,166,167, 17[0, 1, 4, 5, 6, 7, 8], 18[0-9],191,198,199
// 移动号段： 134,135,136,137,138,139,147,150,151,152,157,158,159,178,182,183,184,187,188,198
// 联通号段： 130,131,132,145,146,155,156,166,167,175,176,185,186
// 电信号段： 133,141,153,174,177,180,181,189,191,199
// 虚拟运营商移动号段： 165,1703,1705,1706
// 虚拟运营商联通号段： 1704,1707,1708,1709,171
// 虚拟运营商电信号段： 1700,1701,1702
const verifyPhone = function (val) {

  let MOBILE = "^1(3[0-9]|4[014-7]|5[0-35-9]|6[5-7]|7[014-8]|8[0-9]|9[189])\\d{8}$";

  let ISEMAIL = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$"

  let EMAIL = "^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"

  // 移动
  let CM = "^1(3[4-9]|4[478]|5[0-27-9]|7[8]|8[2-478]|98)\\d{8}$";
  // 联通
  let CU = "^1(3[0-2]|4[56]|5[56]|6[67]|7[56]|8[56])\\d{8}$";
  // 电信
  let CT = "^1(33|41|53|7[47]|8[019]|9[19])\\d{8}$";
  // 虚拟移动
  let VirtualCM = "(^165\\d{8}$)|(^170[356]\\d{7}$)";
  // 虚拟联通
  let VirtualCU = "(^170[47-9]\\d{7}$)|(^171\\d{8}$)";
  // 虚拟电信
  let VirtualCT = "^170[0-2]\\d{7}$";

  let dics = [
    {name: "MOBILE", rule: MOBILE},
    {name: "CM", rule: CM},
    {name: "CU", rule: CU},
    {name: "CT", rule: CT},
    {name: "VirtualCM", rule: VirtualCM},
    {name: "VirtualCU", rule: VirtualCU},
    {name: "VirtualCT", rule: VirtualCT}];

  // forEach 的 return 无法跳出循环
  // dics.forEach(item => {
  // dics.some(item => {
  let res = "";
  if (new RegExp(dics[0].rule).test(val)) {
    for (let i = 0; i < dics.length; i++) {
      let item = dics[i];
      let reg = new RegExp(item.rule);
      let result = reg.test(val);
      if (item.name === "MOBILE" && !result) {
        break; // is not a mobile
      } else if (item.name === "MOBILE") {
        continue; // is a mobile
      }

      if (result) {
        res = item.name;
        break;
      } else {
        continue;
      }
    }
  } else if (new RegExp(ISEMAIL).test(val)) {
    if (new RegExp(EMAIL).test(val)) {
      res = 'EMAIL'
    } else {
      res = 'notemail'
    }
  }

  return res;
};

const verifyCustom = function (val, rule) {
  let reg = new RegExp(rule);
  let result = reg.test(val);
  return result;
};

const util = {
  setSessionStorage: setSessionStorage,
  getSessionStorage: getSessionStorage,
  removeSessionStorage: removeSessionStorage,
  getQueryObject: getQueryObject,
  json2Param: json2Param,
  param2Obj: param2Obj,
  html2Text: html2Text,
  verifyPhone: verifyPhone,
  verifyCustom: verifyCustom,
};

export {
  util,
  install
}

/**
 * 日期格式化
 * let now=(new Date()).Format("yyyy-MM-dd hh:mm:ss");
 * (new Date()).Format("yyyy-MM-dd hh:mm:ss");//2018-01-22 12:00:00
 * (new Date()).Format("yyyy-MM-dd hh:mm");   //2018-01-22 12:00
 * (new Date()).Format("yyyy-MM-dd hh");      //2018-01-22 12
 * (new Date()).Format("yyyy-MM-dd");         //2018-01-22
 * (new Date()).Format("yyyy-MM");            //2018-01
 * (new Date()).Format("yyyy");               //2018
 */
Date.prototype.Format = function (format) {
  let o = {
    "M+": this.getMonth() + 1,  //month
    "d+": this.getDate(),     //day
    "h+": this.getHours(),    //hour
    "m+": this.getMinutes(),  //minute
    "s+": this.getSeconds(), //second
    "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
    "S": this.getMilliseconds() //millisecond
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
};

/**
 * 日期加减换算
 * "d","m","y" 分别为日,月,年   "-1"为在当前日期基础上倒流一个单位
 * new Date().DateAdd('d',-1).Format('yyyy-MM-dd hh:mm:ss');//今天前一天(昨天)
 */
Date.prototype.DateAdd = function (interval, number) {
  number = parseInt(number);
  let date = new Date(this.getTime());

  switch (interval) {
    case "y":
      date.setFullYear(this.getFullYear() + number);
      break;
    case "m":
      date.setMonth(this.getMonth() + number);
      break;
    case "d":
      date.setDate(this.getDate() + number);
      break;
    case "w":
      date.setDate(this.getDate() + 7 * number);
      break;
    case "h":
      date.setHours(this.getHours() + number);
      break;
    case "n":
      date.setMinutes(this.getMinutes() + number);
      break;
    case "s":
      date.setSeconds(this.getSeconds() + number);
      break;
    case "l":
      date.setMilliseconds(this.getMilliseconds() + number);
      break;
  }
  return date;
};

/**
 * 周的开始时间
 * (new Date()).WeekStart(0).Format('yyyy-MM-dd 00:00:00')     本周开始时间
 * (new Date()).WeekStart(-1).Format('yyyy-MM-dd 00:00:00')     上周开始时间
 */
Date.prototype.WeekStart = function (n) {
  let number = n || 0;
  let day = this.getDay();//周几 1 、2、3、4、5、6、0
  //当周日时,getDay()会返回0,此时将day=7;
  if (day === 0) {
    day = 7;
  }
  return this.DateAdd('d', -(day - 1 - 7 * number))
};

/**
 * 周的结束时间
 * (new Date()).WeekEnd(0).Format('yyyy-MM-dd 00:00:00')     本周开始时间
 * (new Date()).WeekEnd(-1).Format('yyyy-MM-dd 00:00:00')     上周开始时间
 */
Date.prototype.WeekEnd = function (n) {
  let number = n || 0;
  let day = this.getDay();//周几 1 、2、3、4、5、6、0
  //当周日时,getDay()会返回0,此时将day=7;
  if (day === 0) {
    day = 7;
  }
  return this.DateAdd('d', (7 - day + 7 * number))
};

/**
 * 月的开始时间
 * (new Date()).MonthStart('d',1).Format('yyyy-MM-dd 00:00:00');
 */
Date.prototype.MonthStart = function (n) {
  let number = n || 0;
  let nowday = this.Format("d");
  //当月第一天
  return this.DateAdd('d', -(nowday - 1));
};

/**
 * 月的结束时间
 * (new Date()).MonthEnd('d',1).Format('yyyy-MM-dd 00:00:00');
 */
Date.prototype.MonthEnd = function (n) {
  let number = n || 0;
  let nowday = this.Format("d");
  let days = this.MonthDays();
  //当月第一天
  return this.DateAdd('d', (days - nowday));
};

/**
 * 获得某月的天数
 * */
Date.prototype.MonthDays = function (m) {
  let myMonth = m || this.getMonth();
  let nowYear = this.getYear(); //当前年
  let monthStartDate = new Date(nowYear, myMonth, 1);
  let monthEndDate = new Date(nowYear, myMonth + 1, 1);
  let days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
  return days;
};


// var SIGN_REGEXP = /([yMdhsm])(\1*)/g;
// var DEFAULT_PATTERN = 'yyyy-MM-dd';
// function padding(s, len) {
//   var len = len - (s + '').length;
//   for (var i = 0; i < len; i++) { s = '0' + s; }
//   return s;
// }
//
//
// const getQueryStringByName = function (name) {
//   var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
//   var r = window.location.search.substr(1).match(reg);
//   var context = "";
//   if (r != null)
//     context = r[2];
//   reg = null;
//   r = null;
//   return context == null || context == "" || context == "undefined" ? "" : context;
// };
